package org.example;

import java.util.ArrayDeque;
import java.util.Deque;

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};

public class Test2 {
    //leetcode 116 填充每个结点的下一个右侧结点指针 https://leetcode.cn/problems/populating-next-right-pointers-in-each-node/description/
    //
    public Node connect(Node root) {
        if (root == null) return root;
        Deque<Node> deque = new ArrayDeque<>();
        deque.add(root);
        while (!deque.isEmpty()) {
            int count = deque.size();
            while (count > 0) {
                Node tmp = deque.poll();
                if (tmp.left != null) deque.add(tmp.left);
                if (tmp.right != null) deque.add(tmp.right);
                if (count != 1) tmp.next = deque.peek();
                else tmp.next = null;
                count--;
            }
        }
        return root;
    }

    public Node connect2(Node root) {
        if (root == null) return root;
        Deque<Node> deque = new ArrayDeque<>();
        deque.add(root);
        while (!deque.isEmpty()) {
            int count = deque.size();
            while (count > 0) {
                Node tmp = deque.poll();
                if (tmp.left != null) {
                    deque.add(tmp.left);
                    tmp.left.next = tmp.right;
                }
                if (tmp.right != null) {
                    deque.add(tmp.right);
                    if (count != 1) {
                        tmp.right.next = deque.peek().left;
                    }
                }
                count--;
            }
        }
        return root;
    }
}
